package encrypt

import (
	"encoding/json"
	"errors"
	"github.com/tidwall/gjson"
	"reflect"
)

/**
 * 将数据转换为json字符串
 * @param data interface{} 任意类型数据,支持结构体，map，切片，数组,字符串
 */
func convertDataToJson(data interface{}) (string, error) {
	if data == nil {
		return "{}", nil
	}
	//判断data是否为结构体类型,map类型，切片类型，数组类型,如果是则转换为json字符串
	kind := reflect.TypeOf(data).Kind()
	if kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice || kind == reflect.Array {
		bodyJsonByte, err := json.Marshal(data)
		if err != nil {
			return "", err
		}
		bodyJsonStr := string(bodyJsonByte)
		if bodyJsonStr == "" || bodyJsonStr == "null" || bodyJsonStr == "NULL" || bodyJsonStr == "nil" {
			bodyJsonStr = "{}"
		}
		return bodyJsonStr, nil
	}

	if kind == reflect.String {
		return data.(string), nil
	}

	return "", errors.New("data type is not support")
}

// 将JSON字符串转换为map
func convertJsonToMap(jsonStr string) (map[string]interface{}, error) {
	var data map[string]interface{}
	err := json.Unmarshal([]byte(jsonStr), &data)
	if err != nil {
		return nil, err
	}
	return data, nil
}

// 将JSON字符串转换为结构体
func convertJsonToStruct(jsonStr string, result interface{}) error {
	err := json.Unmarshal([]byte(jsonStr), result)
	if err != nil {
		return err
	}
	return nil
}

// 将JSON字符串转换为切片
func convertJsonToSlice(jsonStr string, result interface{}) error {

	err := json.Unmarshal([]byte(jsonStr), &result)
	if err != nil {
		return err
	}
	return nil
}

// 获取字符串json中的某个值
func getJsonObjValue(json string, path ...string) ([]gjson.Result, error) {
	if !gjson.Valid(json) {
		return nil, errors.New("invalid json")
	}
	results := gjson.GetMany(json, path...)
	return results, nil
}
